<template>
  <div
    v-if="tabsInfo"
    :class="[tabsInfo.slotTab ? 's-tab-nav' : 's-tab-wrap', { 'is-active': isActive }, { 'is-disabled': disabled }]"
    :style="
      tabsInfo.slotTab
        ? 'color:' + $sTheme(disabled ? tabsInfo.disabledColor : isActive ? tabsInfo.activeColor : tabsInfo.color)
        : ''
    "
    @click="navClick"
  >
    <slot v-if="tabsInfo.slotTab"></slot>
    <div v-else class="s-tab-panel">
      <slot v-if="!tabsInfo.lazyRender || info.isRender"></slot>
    </div>
  </div>
</template>

<script>
import getParentUntil from '../../utils/getParentUntil';

/**
 * s-tab s-tabs组件的子组件
 * @description 必须使用s-tabs组件包裹使用
 * @property {String} title 标题
 * @property {Number|String} name 匹配标识符和s-tabs的v-model值对应，默认使用下标索引匹配
 * @property {Boolean} disabled 是否禁用
 * @example <s-tab title="菜单1"></s-tab>
 */
export default {
  name: 'STab',
  props: {
    title: {
      type: String,
      default: '',
    },
    name: {
      type: [Number, String],
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      info: {
        title: '',
        name: '',
        disabled: false,
        isRender: false,
      },
    };
  },
  computed: {
    isActive() {
      return this.$tabs.navContextList.length && this.$tabs.navContextList[this.$tabs.current] == this;
    },
    tabsInfo() {
      return {
        slotTab: this.$tabs.slotTab,
        navWidth: this.$tabs.navWidth,
        color: this.$tabs.color,
        activeColor: this.$tabs.activeColor,
        disabledColor: this.$tabs.disabledColor,
        lazyRender: this.$tabs.lazyRender,
      };
    },
  },
  watch: {
    title: {
      immediate: true,
      handler() {
        this.info.title = this.title;
      },
    },
    name: {
      immediate: true,
      handler() {
        this.info.name = this.name;
      },
    },
    disabled: {
      immediate: true,
      handler() {
        this.info.disabled = this.disabled;
      },
    },
  },
  created() {
    this.$tabs = getParentUntil(this, 'STabs');
    this.$tabs.navInfoList = this.$tabs.navInfoList.concat(this.info);
    this.$tabs.navContextList = this.$tabs.navContextList.concat(this);
  },
  beforeDestroy() {
    this.$tabs.navInfoList = this.$tabs.navContextList.filter(item => item !== this.info);
    this.$tabs.navContextList = this.$tabs.navContextList.filter(item => item !== this);
  },
  methods: {
    navClick() {
      if (this.$tabs.slotTab) {
        this.$tabs.navContextList.some((item, index) => {
          if (item == this) {
            this.$tabs.navClick(index, item);
            return true;
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.s-tab-wrap {
  width: 100%;
  height: 0;
  font-size: 28rpx;
  flex-shrink: 0;
  white-space: normal;
  overflow: hidden;
  box-sizing: border-box;

  &.is-active {
    height: auto;
    overflow: visible;
  }
}
</style>
